"use client"

import {useState} from "react"
import {Button} from "@/components/ui/button"
import {Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle} from "@/components/ui/card"
import {Textarea} from "@/components/ui/textarea"
import {Input} from "@/components/ui/input"
import {Label} from "@/components/ui/label"
import {ScrollArea} from "@/components/ui/scroll-area"
import {Clipboard, RefreshCw} from "lucide-react"
import type {JsonPlan, Step} from "@/lib/types"
import {useToast} from "@/hooks/use-toast"

export function JsonPlanPanel() {
    const {toast} = useToast()
    const [userRequirements, setUserRequirements] = useState("")
    const [userRequirementsBrief, setUserRequirementsBrief] = useState("")
    const [numberOfSteps, setNumberOfSteps] = useState(10)
    const [generatedPlan, setGeneratedPlan] = useState<JsonPlan | null>(null)
    const [isGenerating, setIsGenerating] = useState(false)

    // 模板步骤
    const templateSteps: Step[] = [
        {
            step_id: 1,
            step_name: "构建Tailwind CSS配置规范",
            step_description: "创建Tailwind CSS的配置文件，定义主题颜色、字体、间距等，确保统一的样式基础。",
        },
        {
            step_id: 2,
            step_name: "定义Tailwind CSS扩展规则",
            step_description: "利用`@layer`指令扩展自定义样式，制定插件和样式的复用规则。",
        },
        {
            step_id: 3,
            step_name: "Tailwind CSS响应式设计规范",
            step_description: "确保所有生成的页面能够适配不同屏幕，使用Tailwind的响应式类进行布局调整。",
        },
        {
            step_id: 4,
            step_name: "制定Vue3组合式API使用规范",
            step_description: "明确规定在Vue3中使用组合式API而非选项式API，确保组件逻辑清晰和响应式数据的管理。",
        },
        {
            step_id: 5,
            step_name: "Vue3生命周期钩子的使用规范",
            step_description: "按照Vue3的生命周期钩子的顺序使用`onMounted`、`onUpdated`等钩子，避免不必要的副作用。",
        },
        {
            step_id: 6,
            step_name: "编写TypeScript类型规范",
            step_description: "定义清晰的类型规则，使用类型推导，确保代码的类型安全性，避免不必要的类型声明。",
        },
        {
            step_id: 7,
            step_name: "TypeScript泛型使用规范",
            step_description: "制定规范，合理使用泛型增强代码复用性，避免过度复杂化。",
        },
        {
            step_id: 8,
            step_name: "定义输入输出协议",
            step_description:
                "规范化系统与开发者的交互协议，定义输入格式（如JSON）和输出格式（如Tailwind CSS样式、Vue3组件代码）。",
        },
        {
            step_id: 9,
            step_name: "设计代码生成引擎架构",
            step_description: "搭建代码生成引擎框架，支持根据用户输入生成符合规范的页面和组件代码。",
        },
        {
            step_id: 10,
            step_name: "实现模板引擎",
            step_description: "开发支持参数化的模板引擎，能够根据不同输入生成相应的组件结构和样式。",
        },
        {
            step_id: 11,
            step_name: "设计规则引擎",
            step_description: "设计一个规则引擎，根据输入需求自动选择适合的组件和样式配置。",
        },
        {
            step_id: 12,
            step_name: "集成代码格式化工具",
            step_description: "集成Prettier等工具，确保生成的代码符合一致的风格并进行自动格式化。",
        },
        {
            step_id: 13,
            step_name: "开发规范校验层",
            step_description: "在代码生成前进行规范校验，检查生成的代码是否符合预定义的编码规范。",
        },
        {
            step_id: 14,
            step_name: "开发原子组件库",
            step_description: "根据常见UI需求，设计并实现可复用的原子组件，如按钮、输入框等。",
        },
        {
            step_id: 15,
            step_name: "组件属性化设计",
            step_description: "为组件定义可配置属性，使其能够通过参数化控制样式和行为，增加组件的可复用性。",
        },
    ]

    // 生成JSON计划
    const generatePlan = () => {
        setIsGenerating(true)

        // 模拟处理时间
        setTimeout(() => {
            // 根据请求的步骤数量创建步骤
            const steps: Step[] = []

            // 生成请求的步骤数量
            for (let i = 0; i < numberOfSteps; i++) {
                if (i < templateSteps.length) {
                    // 使用现有步骤
                    steps.push({...templateSteps[i], step_id: i + 1})
                } else {
                    // 生成新步骤
                    steps.push({
                        step_id: i + 1,
                        step_name: `步骤 ${i + 1}`,
                        step_description: `这是自动生成的步骤 ${i + 1}，请根据实际需求修改。`,
                    })
                }
            }

            // 创建JSON计划
            setGeneratedPlan({
                user_requirements: userRequirements,
                user_requirements_brief: userRequirementsBrief,
                steps: steps,
                number_of_steps: steps.length,
            })

            setIsGenerating(false)

            toast({
                title: "JSON计划生成成功",
                description: `已生成包含 ${steps.length} 个步骤的计划`,
            })
        }, 1000)
    }

    // 格式化JSON以便显示
    const formattedJson = generatedPlan ? JSON.stringify(generatedPlan, null, 2) : ""

    // 复制JSON到剪贴板
    const copyToClipboard = () => {
        if (!formattedJson) return

        navigator.clipboard.writeText(formattedJson)
        toast({
            title: "复制成功",
            description: "JSON计划已复制到剪贴板",
        })
    }

    // 重置表单
    const resetForm = () => {
        setUserRequirements("")
        setUserRequirementsBrief("")
        setNumberOfSteps(10)
        setGeneratedPlan(null)
    }

    // 加载示例数据
    const loadExample = () => {
        setUserRequirements(
            "设计并实现一个TailwindCSS + Vue3 + TypeScript的页面和组件生成助手，包括技术栈规范体系构建、Prompt架构设计、组件生成系统开发等。",
        )
        setUserRequirementsBrief("创建一个代码生成工具，用于生成符合规范的Vue3组件和页面，集成TailwindCSS和TypeScript。")
        setNumberOfSteps(15)
    }

    return (
        <div className="space-y-6">
            <Card>
                <CardHeader>
                    <CardTitle>JSON计划生成器</CardTitle>
                    <CardDescription>为TailwindCSS + Vue3 + TypeScript页面和组件生成结构化的JSON计划</CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                    <div className="space-y-2">
                        <Label htmlFor="userRequirements">详细需求描述</Label>
                        <Textarea
                            id="userRequirements"
                            value={userRequirements}
                            onChange={(e) => setUserRequirements(e.target.value)}
                            placeholder="请输入详细的需求描述..."
                            rows={6}
                        />
                    </div>

                    <div className="space-y-2">
                        <Label htmlFor="userRequirementsBrief">需求简述</Label>
                        <Textarea
                            id="userRequirementsBrief"
                            value={userRequirementsBrief}
                            onChange={(e) => setUserRequirementsBrief(e.target.value)}
                            placeholder="请输入需求的简短概述..."
                            rows={3}
                        />
                    </div>

                    <div className="space-y-2">
                        <Label htmlFor="numberOfSteps">步骤数量</Label>
                        <Input
                            id="numberOfSteps"
                            type="number"
                            min={1}
                            max={50}
                            value={numberOfSteps}
                            onChange={(e) => setNumberOfSteps(Number.parseInt(e.target.value))}
                        />
                    </div>
                </CardContent>
                <CardFooter className="flex justify-between">
                    <div className="flex space-x-2">
                        <Button variant="outline" onClick={resetForm}>
                            重置
                        </Button>
                        <Button variant="outline" onClick={loadExample}>
                            <RefreshCw className="mr-2 h-4 w-4"/>
                            加载示例
                        </Button>
                    </div>
                    <Button onClick={generatePlan}
                            disabled={isGenerating || !userRequirements || !userRequirementsBrief}>
                        {isGenerating ? "生成中..." : "生成JSON计划"}
                    </Button>
                </CardFooter>
            </Card>

            <Card>
                <CardHeader className="flex flex-row items-center justify-between">
                    <div>
                        <CardTitle>生成的JSON计划</CardTitle>
                        <CardDescription>可以复制并用于代码生成系统</CardDescription>
                    </div>
                    {generatedPlan && (
                        <Button variant="outline" size="sm" onClick={copyToClipboard}>
                            <Clipboard className="mr-2 h-4 w-4"/>
                            复制JSON
                        </Button>
                    )}
                </CardHeader>
                <CardContent>
                    <ScrollArea className="h-[400px] w-full rounded-md border">
                        {generatedPlan ? (
                            <pre className="p-4 text-sm font-mono">{formattedJson}</pre>
                        ) : (
                            <div className="flex items-center justify-center h-full text-gray-500">
                                {isGenerating ? <p>生成JSON计划中...</p> :
                                    <p>填写表单并点击"生成JSON计划"按钮来生成JSON</p>}
                            </div>
                        )}
                    </ScrollArea>
                </CardContent>
            </Card>
        </div>
    )
}
